package com.etc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.etc.entity.Counter;
import com.etc.entity.Role;
import com.etc.tools.DBTools;

public class CounterDAO {

	
	DBTools tool = new DBTools();
	Connection conn = tool.getConnection();
	RoleDAO roleDao = new RoleDAO();
	//查找所有的用户
	//登录处理的是否使用，先获取系统所有的账号，放进集合，然后客户端返回的账号密码进行匹配，匹配成功表示存在此账户
	public ArrayList<Counter> findAllCounter() {
		String sql = "select * from T_USER_COUNTER";
		PreparedStatement ps = null;
		ArrayList<Counter> counters = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql);
			ResultSet set = ps.executeQuery();
			while(set.next()) {  
				//查找一个账户时，需要查找此账号旗下的所有角色，需要下面的这个方法
				ArrayList<Role> roles = roleDao.findAllRoleByUserId(set.getString("id"));
				Counter counter = new Counter(set.getString("id"), set.getString("login_id"), 
						set.getString("login_pass"), roles);
				counters.add(counter);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return counters;
	}
	//添加一个用户，注册用
	public void addCounter(Counter counter) {
		String sql = "insert into T_USER_COUNTER values(?,?,?)";
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, counter.getLoginId());
			ps.setString(2, counter.getPassword());
			ps.setString(3, counter.getId());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}
